import React, {useRef, useEffect, useState, createElement} from 'react';
import {Modal, message, Form, Input, Select, Radio, Dropdown, Space, Pagination} from 'antd';
import {icons} from '../../../components/Index';
import _ from 'lodash';
import axios from 'axios';
import {get, post} from "../../../service";

function ModalForm(props) {
    const [currentIcons, setCurrentIcons] = useState(icons.slice(0, 10));
    const [allIcons, setAllIcons] = useState(icons);
    const formRef = useRef(null);
    const [icon, setIcon] = useState(''); // 图标
    const [pName, setPName] = useState('');

    const onCancel = () => {
        props.dispatch({
            type: 'hideModalForm'
        });
    };

    const layout = {
        labelCol: {span: 4},
        wrapperCol: {span: 20},
    };

    const onSave = (values) => {
        if (props.title === '新增') {
            post('/api/menu/add', {...values, pid: props.data.pid}).then((res) => {
                message.success('操作成功');
                onCancel(); // 关闭弹窗
                props.refreshList(); // 刷新列表
                window.dispatchEvent(new Event('refreshMenus'));
            });
            return;
        }
        post('/api/menu/update', {
            ...values,
            pid: props.data.pid || undefined,
            id: props.data.id
        }).then((res) => {
            onCancel(); // 关闭弹窗
            props.refreshList(); // 刷新列表
            window.dispatchEvent(new Event('refreshMenus'));
        });

    };

    const onIconFilter = (e) => {
        let {value} = e.target;
        value = value.trim();
        const newIcons = []; // 存放过滤之后的数据
        if (value) {
            icons.forEach(item => {
                if (_.lowerCase(item.name).indexOf(_.lowerCase(value)) !== -1) {
                    newIcons.push(item);
                }
            });
            setAllIcons(newIcons);
            setCurrentIcons(newIcons.slice(0, 10));
            setIcon(value);
            return;
        }
        setAllIcons(icons);
        setCurrentIcons(icons.slice(0, 10));
        setIcon(value);
    };

    const onIconChange = (e) => {
        // 获取到被选中的图标的 value 值
        const {value} = e.target;
        setIcon(value);
        // 手动设置 icon
        formRef.current.setFieldsValue({icon: value});
    };

    useEffect(() => {
        const {data = {}} = props;
        // 设置 form 表单初数据
        formRef.current.setFieldsValue(data);
        setIcon(data.icon);
        // 根据 pid 获取父级菜单名称
        if (data.pid && data.pid !== -1) {
            get('/api/menu/getMenuName', {id: data.pid}).then(response => {
                setPName(response.record.name);
            });
        }
    }, [props]);

    const readonly = props.title === '详情';

    return (
        <Modal
            visible
            width={600}
            title={props.title}
            onCancel={onCancel}
            onOk={() => formRef.current.submit()}
            className={readonly ? 'm-readonly-modal' : ''}
        >
            <Form {...layout} ref={formRef} onFinish={onSave}>
                <Form.Item label="父菜单">
                    {pName || '无'}
                </Form.Item>
                <Form.Item label="菜单名称" name="name" rules={[{required: true}]}>
                    <Input/>
                </Form.Item>
                <Form.Item label="访问路径" name="linkUrl" rules={[{required: true}]}>
                    <Input/>
                </Form.Item>
                <Form.Item label="打开方式" name="openType" rules={[{required: true}]}>
                    <Select>
                        <Select.Option value="1">当前窗口</Select.Option>
                        <Select.Option value="2">新窗口</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label="图标" name="icon" rules={[{required: true}]}>
                    <Dropdown
                        trigger={['click']}
                        overlayStyle={{background: '#fff', padding: 10}}
                        overlay={
                            <>
                                <Radio.Group onChange={onIconChange}>
                                    <Space direction="vertical">
                                        {currentIcons.map(item => (
                                            <Radio value={item.name} key={item.name}>
                                                {createElement(item.renderFn)}
                                                <span style={{marginLeft: 5}}>{item.name}</span>
                                            </Radio>
                                        ))}
                                    </Space>
                                </Radio.Group>
                                <div style={{textAlign: 'right', padding: 10}}>
                                    <Pagination
                                        showSizeChanger={false}
                                        size="small"
                                        total={allIcons.length}
                                        onChange={(page, pageSize) => {
                                            setCurrentIcons(allIcons.slice(pageSize * (page - 1), pageSize * page));
                                        }}
                                    />
                                </div>
                            </>
                        }
                    >
                        <Input
                            prefix={createElement((_.find(allIcons, item => item.name === icon) || {}).renderFn || 'span')}
                            onChange={onIconFilter}
                            value={icon}
                        />
                    </Dropdown>
                </Form.Item>
                <Form.Item label="权限" name="isOfAdmin" rules={[{required: true}]}>
                    <Radio.Group>
                        <Radio value={1}>仅超管可见</Radio>
                        <Radio value={2}>不限</Radio>
                    </Radio.Group>
                </Form.Item>
            </Form>
        </Modal>
    );
}

export default ModalForm;
